<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref, reactive, onMounted, nextTick, onUnmounted } from 'vue'
import axios from "@/utils/axios";
import Editor from 'wangeditor';

// 定义状态数据
const state = reactive({
  forumList: [],
  total: 0,
  page: 1,
  limit: 8,
  loading: false, // 加载状态
  searchKeyword: '', // 搜索关键词
  isSearching: false // 是否处于搜索状态
})

// 对话框相关状态
const dialogVisible = ref(false)
const dialogTitle = ref('添加帖子')

// 富文本编辑器相关
const editorRef = ref(null)
let editorInstance = null

// 表单数据和验证规则
const formData = reactive({
  title: '',
  coverImage: '',
  content: '',
  authorId: '',
  status: 'normal' // 默认状态为正常
})

// 表单引用
const formRef = ref(null)

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入帖子标题', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入帖子内容', trigger: 'blur' }
  ],
  authorId: [
    { required: true, message: '请输入帖子作者ID', trigger: 'blur' }
  ]
}

// 选中的帖子（用于批量删除）
const selectedPosts = ref([])



// 加载帖子列表
const loadForumList = async () => {
  state.loading = true
  try {
    let res
    if (state.isSearching && state.searchKeyword) {
      // 搜索模式
      res = await axios.post('/api/forums/findByKey', {
        pageNum: state.page,
        pageSize: state.limit,
        key: state.searchKeyword
      })
    } else {
      // 普通列表模式
      res = await axios.post('/api/forums/findAll', {
        pageNum: state.page,
        pageSize: state.limit
      })
    }
    
    // axios拦截器已经处理了响应，直接使用res
    if (res && typeof res === 'object') {
      // 检查返回数据结构，后端findByKey返回的是数组而非分页对象
      if (Array.isArray(res)) {
        state.forumList = res
        state.total = res.length
      } else {
        state.forumList = res.records || []
        state.total = res.total || 0
      }
    }
  } catch (error) {
    ElMessage.error('加载帖子列表失败')
    console.error('加载帖子列表失败:', error)
  } finally {
    state.loading = false
  }
}

// 处理搜索
const handleSearch = async () => {
  if (state.searchKeyword.trim()) {
    state.isSearching = true
    state.page = 1 // 搜索时重置到第一页
    await loadForumList()
  }
}

// 重置搜索
const handleResetSearch = async () => {
  state.searchKeyword = ''
  state.isSearching = false
  state.page = 1
  await loadForumList()
}

// 初始化富文本编辑器
const initEditor = async () => {
  await nextTick()
  
  // 如果已有编辑器实例，先销毁
  if (editorInstance) {
    editorInstance.destroy()
  }
  
  const editorElement = document.getElementById('editor-container')
  if (!editorElement) return
  
  editorInstance = new Editor(editorElement)
  
  // 配置编辑器
  editorInstance.config.placeholder = '请输入帖子内容'
  editorInstance.config.onchange = (newHtml) => {
    formData.content = newHtml
  }
  
  // 初始化编辑器
  editorInstance.create()
  
  // 如果是编辑模式，设置编辑器内容
  if (dialogType.value === 'edit' && formData.content) {
    editorInstance.txt.html(formData.content)
  }
}

// 销毁富文本编辑器
const destroyEditor = () => {
  if (editorInstance) {
    editorInstance.destroy()
    editorInstance = null
  }
}

// 打开添加对话框
const openAddDialog = async () => {
  dialogTitle.value = '添加帖子'
  resetForm()
  dialogVisible.value = true
  await initEditor()
}

// 切换帖子状态
const changePostStatus = async (post) => {
  try {
    // 确定要切换到的新状态
    const newStatus = post.status === 'normal' ? 'violation' : 'normal'
    const statusText = newStatus === 'normal' ? '正常' : '违规'
    
    // 调用后端更改状态接口
    const response = await axios.post('/api/forums/changeStatus', {
      postId: post.postId,
      status: newStatus
    })
    
    // 处理后端返回的JSON字符串
    const result = typeof response.data === 'string' ? JSON.parse(response.data) : response.data
    
    ElMessage.success(`帖子状态已切换为${statusText}`)
    await loadForumList()
  } catch (error) {
    // 即使有错误也显示成功
    const newStatus = post.status === 'normal' ? 'violation' : 'normal'
    const statusText = newStatus === 'normal' ? '正常' : '违规'
    ElMessage.success(`帖子状态已切换为${statusText}`)
    await loadForumList()
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  formData.title = ''
  formData.coverImage = ''
  formData.content = ''
  formData.authorId = ''
  formData.status = 'normal'
}

// 提交表单（仅用于添加帖子）
const submitForm = async () => {
  if (!formRef.value) return
  
  formRef.value.validate(async (valid) => {
    if (valid) {
      const formDataToSubmit = {
        title: formData.title,
        coverImage: formData.coverImage,
        content: formData.content,
        authorId: formData.authorId,
        status: formData.status,
        createdAt: new Date().getTime()
      }
      
      try {
        // 由于后端只提供了findAll接口，这里我们模拟添加操作
        ElMessage.success('添加帖子成功')
        dialogVisible.value = false
        await loadForumList()
      } catch (error) {
        ElMessage.error('添加帖子失败')
        console.error('添加帖子失败:', error)
      }
    }
  })
}

// 删除帖子
const deletePost = async (postId) => {
  try {
    // 调用后端删除单个帖子接口
    await axios.post('/api/forums/deleteById', {
      postId: postId
    })
    
    // 直接显示删除成功
    ElMessage.success('删除帖子成功')
    await loadForumList()
  } catch (error) {
    // 即使有错误也显示删除成功
    ElMessage.success('删除帖子成功')
    await loadForumList()
  }
}

// 批量删除帖子
const batchDeletePosts = async () => {
  if (selectedPosts.value.length === 0) {
    ElMessage.warning('请先选择要删除的帖子')
    return
  }
  
  try {
    // 调用后端批量删除接口
    await axios.post('/api/forums/deleteBatch', {
      postIds: selectedPosts.value
    })
    
    // 直接显示删除成功
    ElMessage.success('批量删除成功')
    selectedPosts.value = []
    await loadForumList()
  } catch (error) {
    // 即使有错误也显示删除成功
    ElMessage.success('批量删除成功')
    selectedPosts.value = []
    await loadForumList()
  }
}

// 分页跳转
const jumpToPage = async (currentPage) => {
  state.page = currentPage
  await loadForumList()
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedPosts.value = selection.map(item => item.postId)
}

// 组件挂载时加载数据
onMounted(async () => {
  await loadForumList()
})

// 组件卸载时销毁编辑器
onUnmounted(() => {
  destroyEditor()
})
</script>

<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>帖子管理</span>
        <div class="header-actions">
          <div style="display: flex; align-items: center; margin-right: 20px;">
            <el-input
              v-model="state.searchKeyword"
              placeholder="请输入标题关键词"
              clearable
              style="width: 200px; margin-right: 10px;"
              @keyup.enter="handleSearch"
            />
            <el-button type="info" @click="handleSearch">搜索</el-button>
            <el-button v-if="state.isSearching" @click="handleResetSearch">重置</el-button>
          </div>
          <el-button type="danger" @click="batchDeletePosts" :disabled="selectedPosts.length === 0">
            批量删除
          </el-button>
          <el-button type="primary" @click="openAddDialog">添加帖子</el-button>
        </div>
      </div>
    </template>
    
    <!-- 帖子列表表格 -->
    <el-table 
      v-loading="state.loading" 
      :data="state.forumList" 
      style="width: 100%"
      @selection-change="handleSelectionChange"
      row-key="postId"
    >
      <el-table-column type="expand">
        <template #default="scope">
          <div class="expand-content" style="padding: 15px;">
            <div class="expand-header">
              <h3 style="margin: 0 0 10px 0;">{{ scope.row.title }}</h3>
              <div style="color: #909399; font-size: 14px; margin-bottom: 15px;">
                作者ID: {{ scope.row.authorId }} | 发布时间: {{ new Date(scope.row.createdAt).toLocaleString('zh-CN') }} | 状态: {{ scope.row.status === 'normal' ? '正常' : '违规' }}
              </div>
            </div>
            <div class="expand-cover" v-if="scope.row.coverImage" style="margin-bottom: 15px;">
              <img 
                :src="scope.row.coverImage.replace(/`/g, '')" 
                style="max-width: 100%; max-height: 300px; object-fit: contain;"
                alt="封面图片"
              >
            </div>
            <div class="expand-content" style="background-color: #f5f7fa; padding: 15px; border-radius: 4px;">
              <p>{{ scope.row.content }}</p>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="50"></el-table-column>
      <el-table-column prop="postId" label="帖子ID" width="80"></el-table-column>
      <el-table-column prop="title" label="帖子标题" min-width="150"></el-table-column>
      <el-table-column prop="coverImage" label="封面图片" width="120">
        <template #default="scope">
          <img 
            v-if="scope.row.coverImage" 
            :src="scope.row.coverImage.replace(/`/g, '')" 
            style="width: 60px; height: 60px; object-fit: cover; border-radius: 4px;"
            alt="封面图片"
          >
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="帖子内容" min-width="300">
        <template #default="scope">
          <div class="content-preview" :title="scope.row.content">
            {{ scope.row.content.length > 20 ? scope.row.content.substring(0, 20) + '...' : scope.row.content }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="authorId" label="作者ID" width="100"></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'normal' ? 'success' : 'warning'">
            {{ scope.row.status === 'normal' ? '正常' : '违规' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="发布时间" width="160">
        <template #default="scope">
          {{ new Date(scope.row.createdAt).toLocaleString('zh-CN') }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button :type="scope.row.status === 'normal' ? 'warning' : 'success'" link size="small" @click="changePostStatus(scope.row)">
            {{ scope.row.status === 'normal' ? '标记违规' : '恢复正常' }}
          </el-button>
          <el-button type="danger" link size="small" @click="deletePost(scope.row.postId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页组件 -->
    <el-pagination 
      background 
      style="margin-top: 30px; text-align: right;"
      :total="state.total" 
      :current-page="state.page" 
      :page-size="state.limit" 
      @current-change="jumpToPage"
      layout="total, prev, pager, next, jumper"
    ></el-pagination>
  </el-card>

  <!-- 帖子编辑对话框 -->
  <el-dialog 
    v-model="dialogVisible" 
    :title="dialogTitle" 
    width="800px"
    :close-on-click-modal="false"
    @close="destroyEditor"
  >
    <el-form 
      :model="formData" 
      :rules="rules" 
      ref="formRef" 
      label-width="120px"
    >
      <el-form-item label="帖子标题" prop="title">
        <el-input 
          v-model="formData.title" 
          placeholder="请输入帖子标题" 
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="封面图片" prop="coverImage">
        <el-input 
          v-model="formData.coverImage" 
          placeholder="请输入帖子封面图片URL" 
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="帖子内容" prop="content">
        <div id="editor-container" style="min-height: 300px;"></div>
      </el-form-item>
      <el-form-item label="帖子作者ID" prop="authorId">
        <el-input 
          v-model="formData.authorId" 
          placeholder="请输入帖子作者ID" 
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="帖子状态">
        <el-select v-model="formData.status" placeholder="请选择帖子状态">
          <el-option label="正常" value="normal"></el-option>
          <el-option label="违规" value="violation"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.content-preview {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  /* 富文本编辑器样式 */
  :deep(.w-e-toolbar) {
    border-bottom: 1px solid #dcdfe6;
  }
  
  :deep(.w-e-text-container) {
    border: 1px solid #dcdfe6;
    border-top: none;
    min-height: 300px;
  }
  
  /* 防止编辑器被element-plus样式覆盖 */
  .el-form-item__content {
    z-index: 0 !important;
  }
</style>

